import React, { Fragment, useState } from "react";

import { Input, Button, List, Form, Rate } from "antd";
import { SendOutlined } from "@ant-design/icons";

import SessionList from "./components/session_list";
import MessageTip from "./components/message_tip";
import request from "../../api/http_class";
import { getChatResponse } from "../../api/system";
import styles from "./index.module.less";
import "./index.less";

interface Message {
  id?: string;
  role: "user" | "bot";
  content: string;
  reference?: string;
}

const Chat: React.FC = () => {
  const [input, setInput] = useState("");
  const [messages, setMessages] = useState<Message[]>([]);
  const [reference, setReference] = useState<string>();
  const [value, setValue] = useState(3);
  const [form] = Form.useForm();

  const desc = ["很差", "差", "一般", "好", "非常好"];

  // const respNode = (
  // 	<div style={{ float: "right", paddingTop: "10px" }}>
  // 		<Rate tooltips={desc} onChange={setValue} value={value} />
  // 		<span className="ant-rate-text">{desc[value - 1]}</span>
  // 	</div>
  // );

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInput(e.target.value);
  };

  const handleQuery = (e: any) => {
    e.preventDefault();

    if (!input) {
      return;
    }

    request({
      url: `http://121.36.25.135:8888/api/v1/chroma/search/`,
      // url: `http://127.0.0.1:8000/v1/test/`,
      method: "GET",
      data: { query: input },
    }).then(
      (res: any) => {
        console.log(res);
        setReference(res.data);
      },
      (err: any) => {
        console.log(err);
      }
    );
    setInput("");
  };

  const handleSendMessage = (e: any) => {
    e.preventDefault();

    if (!input) {
      return;
    }

    let tmpMessages = [...messages, { role: "user" as const, content: input }];
    setMessages(tmpMessages);
    const data = {
      model: "Qwen-VL-7B",
      messages: [
        {
          role: "user",
          content: input,
        },
      ],
    };

    request({
      // url: `http://121.36.25.135:8888/api/v1/chat/completions/`,
      url: `http://127.0.0.1:8001/api/v1/chat/completions/`,
      method: "POST",
      data: data,
    }).then(
      (res: any) => {
        console.log(res);
        console.log(res.data.choices[0].message.content);
        console.log(res.data.choices[0].message.role);
        tmpMessages = [
          ...tmpMessages,
          {
            content: res.data.choices[0].message.content,
            role: res.data.choices[0].message.role,
            reference: res.data.choices[0].message.reference,
          },
        ];
        setMessages(tmpMessages);
      },
      (err: any) => {
        console.log(err);
      }
    );
    setInput("");
  };

  const handleSendMessage1 = (e: any) => {
    e.preventDefault();
    if (!input) {
      return;
    }
    getChatResponse({ query: input }).then(
      (res: any) => {
        console.log(res);
      },
      (err: any) => {
        console.log(err);
      }
    );
    setInput("");
  };

  const handleRate = (value: any) => {
    console.log(value);
    const values = form.getFieldsValue();
    console.log(values);
  };

  return (
    <Fragment>
      <div className={styles.chat}>
        <h2>药学AI助理</h2>
        <List
          style={{ marginBottom: "120px" }}
          itemLayout="vertical"
          dataSource={messages}
          renderItem={(item: Message) => {
            return (
              <List.Item>
                <div
                  className={
                    item.role === "user" ? "user-message" : "bot-message"
                  }
                >
                  {item.content}
                  <div>
                    {item.role !== "user" ? (
                      <Form form={form} layout="vertical" onFinish={handleRate}>
                        <div style={{ float: "right", paddingTop: "10px" }}>
                          <Form.Item name={"id"} hidden={true}>
                            <Input value={item.id} />
                          </Form.Item>
                          <Form.Item>
                            <Form.Item noStyle name={"rate"}>
                              <Rate
                                tooltips={desc}
                                onChange={handleRate}
                                value={value}
                              />
                            </Form.Item>
                            <span className="ant-rate-text">
                              {desc[value - 1]}
                            </span>
                          </Form.Item>
                        </div>
                      </Form>
                    ) : (
                      <div></div>
                    )}
                  </div>
                  {item.reference && (
                    <div className={reference}>参考资料：{item.reference}</div>
                  )}
                </div>
              </List.Item>
            );
          }}
        />

        <div>
          <Input
            value={input}
            onChange={handleInputChange}
            onPressEnter={handleSendMessage}
            placeholder="请输入您的问题..."
            suffix={
              <Button type="primary" onClick={handleSendMessage}>
                <SendOutlined rev={undefined} /> 发送
              </Button>
            }
          />
        </div>
        <Button type="primary" onClick={handleSendMessage1}>
          <SendOutlined rev={undefined} /> 发送
        </Button>
      </div>
    </Fragment>
  );
};

export default Chat;
